<template>
	<view class="page add-address">
		<!-- 表单信息 start -->
		<view class="addAddr">
 <!--     <view class="cell" v-if="serveList.length > 0">
      	<text class="title">标签</text>
      	<view class="flex align-center">
      		<view v-for='(item,index) in serveList' :key='index' class='cu-tag radius'
      			:class='item.name == default_serve.name? index < 3? "bg-orange":"bg-green radius-left" :"line-black"'
      			@click='changeServe(item)' v-show="item.name">
      			{{item.name}}
      		</view>
      		<view v-if="serveList.length== 4" class='cu-tag radius bg-green left-0 radius-right'
      			@click='addServe(serveList[3].name)'>
      			编辑
      		</view>
      		<view class='cu-tag line-black radius' @click='addServe()' v-if="serveList.length<= 3">+</view>
      	</view>
      </view> -->

			<view class="cell">
				<text class="title"> {{i18n['提货人']}}</text>
				<input type="text" maxlength="8" v-model="name"
					:placeholder="i18n['提货人']" />
			</view>
			<view class="cell">
				<text class="title">{{i18n['联系电话']}}</text>
				<input type="number" maxlength="11" v-model="phone"
					:placeholder="i18n['联系电话']" />
				<text v-if="phone.length > 0" class="margin-right cuIcon-close" @click="clear"
					style="font-size: 36rpx;color:#999;"></text>
			</view>

			<view class="flex justify-between cell margin-top">
				<view class=""> {{i18n['设置默认提货人']}}</view>
				<switch class='theme' @change="handleSwitch" :class="is_default?'checked':''" :checked="is_default?true:false"></switch>
			</view>
		</view>
		<!-- 表单信息 end -->
		<!-- 服务标签弹框 start -->
		<fu-popup v-model="serve_show" mode="bottom" :safe-area-inset-bottom="true">
			<view class="serve-pop flex align-center justify-center" :style="{bottom:keyboardheight+'px'}">
				<input type="text" :placeholder="i18n['请填写标签名称（最多5个字）']" v-model='serveKeyword' maxlength="5" focus
					:adjust-position='false'>
				<button @click='addServeInfo()'>{{i18n['确认']}} </button>
			</view>
		</fu-popup>
		<!-- 服务标签弹框 end -->
		<!-- 底部占位 start -->
		<view class="bottom-status"></view>
		<!-- 底部占位 end -->
		<!-- 提交按钮 start -->
		<view class="bottom-action">
			<view class="btn2" @click="sub_sure">{{i18n['保存']}}</view>
		</view>
		<!-- 提交按钮 end -->

		<!-- 断网监测 start -->
		<fu-notwork></fu-notwork>
		<!-- 断网监测 end -->
	</view>
</template>

<script>
	// 高德地图sdk
	import amapFile from '@/libs/amap-wx.js';
	export default {
		computed: {
			// 合并省市区信息字段
			address() {
				return this.province + this.city + this.district;
			},
		},
		components:{
		},
		data() {
			return {
				keyboardheight: 0, // 键盘高度
				serveKeyword: '', // 服务标签关键字
				serve_show: false, // 服务标签弹框
				serveList: [], // 服务标签
				default_serve: '', // 默认服务标签
				phone: '', // 联系电话
				name: '', // 收货人姓名
				sex: 0, // 性别 0:男 1:女
				is_default: true, // 是否设为默认地址
				edit_id: null, // 是否是修改收货地址
				myAmapFun: null, // 高德地图实例
				province: '', // 省
				city: '', //市
				district: '', //区
				provinceCode: '', // 省 code码
				cityCode: '', //市 code码
				districtCode: '', //区 code码
				addressDesc: '', // 详细地址
				customStyle: {
					'backgroundColor': '#cccccc',
					'color': '#ffffff',
				},// 自定义按钮样式
			};
		},
		/**
		 * @description 页面入参
		 * @param {object} options = [id]
		 * @param {string} id = 修改的地址ID
		 */
		onLoad(options) {
			// 监听键盘高度
			// uni.onKeyboardHeightChange((res) => {
			// 	console.log("键盘监听", res);
			// 	this.keyboardheight = res.height;
			// });
			// 初始化高德地图SDK,记得换成自己的key
			this.myAmapFun = new amapFile.AMapWX({ key: '71e2d1e8fad67225279e724ff7c51e64' });
			//如果是修改地址
			if (options.id) {
				this.edit_id = options.id;
				// 换标题文字
				uni.setNavigationBarTitle({
					title: this.i18n['编辑提货人']
				});
				// 获取要修改的地址信息
				this.get_editAddress();
			} else {
				// 自动定位当前地址
				// 获取默认标签
				// this.getLabelData()
			}
		},
		methods: {
			/**
			 * @func 获取服务标签列表
			 */
			getLabelData(val) {
				this.$api.post(global.apiUrls.getLabel, {}).then(res => {
					if (res.data.code == 1) {
						console.log('服务标签列表', res.data.data)
						this.serveList = res.data.data
						let serve = uni.getStorageSync('DEFAULT_SERVE');
						// 判断是否为编辑
						if (this.edit_id) {
							this.default_serve = {
								id: 0,
								name: val
							}
							var flag = this.serveList.filter((item) => {
								return item.name == val
							})
							if (flag.length == 0) {
								if(this.default_serve.name) this.serveList.push(this.default_serve);
							}
						} else {
							if (serve &&  this.serveList !=0) {
								this.default_serve = this.serveList[0]
								this.serveList.push(JSON.parse(serve))
							}
						}
					} else {
						this.$message.info(res.data.msg);
					}
				}).catch(err => {
					this.$message.info(err.msg);
				})
			},
			/**
			 * @description  自定义服务标签弹窗显示
			 * @param {String} name 回显自定义标签关键词
			 */
			addServe(name) {
				if (name) {
					this.serveKeyword = name
				}
				this.serve_show = true //弹窗显示
			},
			/**
			 * @func 新增服务标签
			 */
			addServeInfo() {
				let val = this.serveKeyword.trim()
				if (val) {
					console.log(this.serveList)
					var flag = this.serveList.filter((item) => {
						return item.name == val
					})
					console.log(flag)
					if (flag.length == 0) {
						this.serve_show = false // 弹窗隐藏
						let serve = { id: 0, name: val }
						// 存在自定义标签
						if (this.serveList.length > 3) {
							this.serveList[3] = serve
						} else {
							this.serveList.push(serve)
						}
						this.default_serve = serve
						if (!this.edit_id) {
							uni.setStorageSync('DEFAULT_SERVE', JSON.stringify(serve));
						}
					} else {
						this.$message.info(this.i18n['标签已存在']);
					}
				} else {
					this.$message.info(this.i18n['请输入内容']);
				}
			},
			/**
			 * @description 切换服务标签
			 * @param {String} item = 服务标签关键字
			 */
			changeServe(item) {
				this.default_serve = item;
			},
			/**
			 * @description 选择性别
			 * @param {String} type = 性别
			 */
			chooseSex(type) {
				this.sex = type;
			},
			/**
			 * @func 获取修改地址信息
			 */
			get_editAddress() {
				this.$api.post(global.apiUrls.postUserInviteGetOneInvite, {
					id: this.edit_id
				}).then(res => {
					console.log(res, '修改的信息');
					if (res.data.code == 1) {
						let data = res.data.data;
						this.name = data.name; // 收货人姓名
						this.phone = data.mobile; // 收货人电话
						this.is_default = data.is_default == '1' ? true : false; // 是否默认
						// 服务标签
						this.getLabelData(data.label_name)

					} else {
						this.$message.info(res.data.msg);
					}
				}).catch(err => {
					this.$message.info(err.msg);
				})
			},
			/**
			 * @func 显示地址选择弹窗
			 */
			showMulLinkageThreePicker() {
				uni.hideKeyboard();
				this.$refs.region.show();
			},
			/**
			 * @description 地址选择回调
			 * @param {Object} val = 地址信息对象
			 */
			onConfirm(val) {
				this.province = val.obj.province.label;
				this.city = val.obj.city.label;
				this.district = val.obj.area.label;
				this.provinceCode = val.value[0];
				this.cityCode = val.value[1];
				this.districtCode = val.value[2];
			},
			/**
			 * @func 切换是否为默认地址
			 */
			handleSwitch(e) {
				this.is_default = e.detail.value;
			},
			/**
			 * @func 定位地址
			 */
			location() {
				let _this = this;
				//#ifdef MP-WEIXIN
				uni.getSetting({
					success(res) {
						// 获取设置成功
						console.log(res.authSetting);
						if (!res.authSetting['scope.userLocation']) {
							// 如果没开启权限提示打开
							uni.openSetting({
								success(res) {
									// 打开成功，提示获取权限
									console.log(res.authSetting);
									uni.authorize({
										scope: 'scope.userLocation',
										success(res) {
											_this.chooseLocation();
										},
										fail(res) {
											console.log(res);
											this.$message.info(this.i18n['打开权限失败']);
										}
									});
								}
							});
						} else {
							_this.chooseLocation();
						}
					}
				});
				//#endif
				this.chooseLocation();
			},
			/**
			 * @func 地图选点
			 */
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						console.log(res, '地图');
						this.myAmapFun.getRegeo({
							location: res.longitude + ',' + res.latitude,
							success: (data) => {
								//成功回调
								console.log('sdk回调', data);
								let regeoData = data[0].regeocodeData.addressComponent;
								this.province = regeoData.province;
                				this.city = Array.isArray(regeoData.city) && (regeoData.city.length == 0) ? regeoData.province: regeoData.city;
								this.district = regeoData.district;
								this.addressDesc = res.address + res.name;
								this.provinceCode = regeoData.adcode.substr(0,2)+'0000';
								this.cityCode = regeoData.adcode.substr(0,4)+'00';
								this.districtCode = regeoData.adcode+'';
							},
							fail: (info) => {
								//失败回调
								console.log(info)
							}
						})
					}
				})
			},

      beforeConfirm(){
        this.$util.debounce(this.sub_sure,1000,true);
      },
			/**
			 * @func 提交表单
			 */
			sub_sure() {
				// 表单验证
				if (this.name.trim() == '') {
					this.$message.info(this.i18n['请输入收货人姓名'] );
					this.name = '';
					return false;
				};
				if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phone)) {
					let text = !this.phone ? this.i18n['请输入手机号']  : this.i18n['手机号格式不正确']  ;
					this.$message.info(text);
					return false;
				}


				let data = {
					name: this.name, // 收货人姓名
					mobile: this.phone, // 收货人手机
					is_default: this.is_default ? '1' : '0', // 是否默认地址
					label_name: this.default_serve?this.default_serve.name:'' // 标签name
				}
				// 判断提交的接口
				let url = global.apiUrls.postUserInviteAddInvite;
				if (this.edit_id) {
					data.id = this.edit_id
					url = global.apiUrls.postUserInviteEditInvite;
				}
        console.log('提交的地址参数',data,url);
				// 提交请求
				this.$api.post(url, data)
					.then(res => {
						console.log(res, '添加/编辑成功');
						if (res.statusCode == 200 && res.data.code == 1) {
							this.$message.info(this.i18n['保存成功']);
              // 通知商品详情页更新地址数据
              uni.$emit('refreshAddress',res.data.data.address_id);
							setTimeout(() => {
								uni.navigateBack()
							}, 800);
						} else {
							this.$message.info(res.data.msg)
						}

					})
					.catch(err => {
						console.log("err: ", err);
					})
			},
			/**
			 * @func 删除地址
			 */
			delAddr() {
				let address_id = this.edit_id;
				this.$util.showModal({
					content: '是否删除该地址',
					success: (res) => {
						if (res.confirm) {
							this.$api.post(global.apiUrls.postUserInviteDelInvite, { address_ids: address_id })
								.then(res => {
									console.log(res);
									if (res.data.code == 1) {
										uni.navigateBack();
									} else {
										this.$message.info(res.msg);
									}
								});
						}
					}

				})
			},
			/**
			 * @func 清除手机号
			 */
			clear() {
				this.phone = '';
			}
		}
	}
</script>
<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background: #FFFFFF;
	}
	.tag{
		padding: 0 16rpx;
		margin-right: 10rpx;
		line-height: 52rpx;
		border: 1rpx solid #333;
	}
	.bottom-status {
		height: 156rpx;
		height: calc(156rpx + constant(safe-area-inset-bottom));
		height: calc(156rpx + env(safe-area-inset-bottom));
	}
	.text-area {
		height: 160rpx !important;
		background-color: #F6F6F6;
		padding: 20rpx;
		border-radius: 8rpx;
	}
 /deep/	.uni-textarea-textarea{
		line-height: 1.5;
	}
	.addAddr {
		padding: 0 20upx;

		.uni-list-cell {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			margin: 20upx 0;
			box-sizing: border-box;
			height: 100upx;
			font-size: 30upx;
			background: #fff;
		}

		.addr {
			font-size: 32upx;
			padding: 30upx 0;
			border-bottom: 1px solid #f5f5f7;
			width: 100%;
			display: flex;
			flex-direction: row;
			align-items: center;

			.addr_title {
				display: inline-block;
				width: 180rpx;
			}

			.chose_addr {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				width: 70%;
			}
		}

		.cell {
			font-size: 32upx;
			display: flex;
			flex-direction: row;
			align-items: center;
			padding: 32rpx 0;
			border-bottom: 1px solid #f5f5f7;

			.title {
				display: inline-block;
				width: 180rpx;
			}

			input {
				flex: 1;
				color: #333;
			}

			.text-area {
				flex: 1;
			}
		}

		.address {
			display: flex;
			flex-direction: column;
			font-size: 32upx;

			.title {
				line-height: 110upx;
			}
		}

		.tips {
			padding: 20upx 0;
			font-size: 26upx;
		}
	}

	.placeholderClass {
		font-size: 32rpx;
		color: #BFBFBF;
	}

	.active {
		color: #ff6567 !important;
	}

	switch::before,
	switch::after {
		content: "";
	}

	.bottom-action {
		position: fixed;
		right: 32rpx;
		left: 32rpx;
		bottom: 56rpx;
		bottom: calc(56rpx + constant(safe-area-inset-bottom));
		bottom: calc(56rpx + env(safe-area-inset-bottom));
		display: flex;

		view {
			height: 88rpx;
			flex: 1;
			line-height: 88rpx;
			text-align: center;
			border-radius: 88rpx;
			color: #FFFFFF;
		}

		.btn2 {
			background: $bgtheme;
		}
	}

	/deep/ uni-switch.checked-green .uni-switch-input {
		background-color: #39b54a !important;
		border-color: #39b54a !important;
		color: #ffffff !important;
	}

	.serve-pop {
		height: 100rpx;
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: #FFFFFF;

		input {
			margin-left: 32rpx;
			width: 528rpx;
			height: 66rpx;
			background: #F6F7F9;
			opacity: 1;
			border-radius: 35rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #99999A;
			text-indent: 1em;
		}

		button {
			width: 140rpx;
			height: 66rpx;
			background: #FF9D00;
			border-radius: 33rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #FFFFFF;
		}
	}

	.left-0 {
		margin-left: 2rpx;
	}

	.radius-left {
		border-top-left-radius: 20rpx;
		border-bottom-left-radius: 20rpx;
	}

	.radius-right {
		border-top-right-radius: 20rpx;
		border-bottom-right-radius: 20rpx;
	}
</style>
